import { Body, Controller, Delete, Get, Param, Post, Put, Query, Req } from '@nestjs/common';
import { ApiBearerAuth, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger';
import { BlogService } from './blog.service';
import { BlogDto } from './dto/blog.dto';
import { decode, sign, verify } from 'jsonwebtoken';

@Controller('')
@ApiTags('博客文章')
export class BlogController {
    constructor(private readonly blogService: BlogService) {}

    @Post('blog')
    @ApiBearerAuth()
    createBlog(@Body() newBlog: BlogDto, @Req() req){
        // 取userId
        //let token = req.headers['authorization'].replace(/\s*/g,"").substr(6);
        let token = req.headers['authorization']
        let userId = parseInt(JSON.parse(JSON.stringify(decode(token))));
        return this.blogService.saveBlog(newBlog, userId)
    }

    @Get('AllBlogs')
    getAllBlogs(){
        return this.blogService.getAllBlogs()
    }

    @Get('blogByQuery')
    @ApiQuery({
        name: 'query',
        required: false
    })
    @ApiQuery({
        name: 'pagenum'
    })
    @ApiQuery({
        name: 'pagesize'
    })
    @ApiQuery({
        name: 'orderBy'
    })
    @ApiQuery({
        name: 'typeId'
    })
    getBlogListByQuery(@Query('query') query, @Query('pagenum') pagenum, @Query('pagesize') pagesize, @Query('orderBy') orderBy, @Query('typeId') typeId){
        return this.blogService.getBlogsByQuery(query, pagenum, pagesize, orderBy, typeId)
    }

    @Get('blog/:blogId')
    @ApiParam({
        name: 'blogId',
        description: '请传入文章Id' 
    })
    getBlogById(@Param('blogId') id){
        return this.blogService.getBlogById(id)
    }

    @Put('updateBlog/:blogId')
    @ApiParam({
        name: 'blogId',
        description: '请传入文章Id' 
    })
    @ApiBearerAuth()
    updateBlogById(@Param('blogId') id, @Body() updatedBlog: BlogDto, @Req() req){
        let token = req.headers['authorization']
        let userId = parseInt(JSON.parse(JSON.stringify(decode(token))));
        return this.blogService.updateBlog(id, updatedBlog, userId)
    }

    @Delete('deleteBlog/:blogId')
    @ApiParam({
        name: 'blogId',
        description: '请传入文章Id' 
    })
    deleteBlogById(@Param('blogId') id){
        return this.blogService.deleteBlog(id)
    }
}
